import * as echarts from './ec/echarts';
const app = getApp();
var timerNum = -1;
Page({

    data: {
        nowDataTime: '--',

        devFlow: '--',
        devAccuFlow: '--',

        bakFlow: '--',
        bakAccuFlow: '--',

        nowRate: '--',


        ec: {
            lazyLoad: true
        },

        ecCanvasId: 'test_ecCanvasId',
        canvasId: 'test_canvasId',
    },

    onLoad: function(options) {},

    onShow: function() {

        this.dataRefreshTimer();
        this.getLatestNowData();

        this.getHourData();
    },

    onReady: function() {},

    dataRefreshTimer: function(e) {
        var that = this;

        timerNum = setTimeout(function() {
            that.getLatestNowData();
            that.dataRefreshTimer();
            // console.log('定时器运行了')
        }, 60000)
    },

    getLatestNowData: function(e) {
        // console.log('开始获取新数据')
        var that = this;

        app.db.collection('nowData').where({
            wellName: '刘庄开采井',

        }).orderBy('ts', 'desc').limit(1).field({
            _id: false,
            nowFlow: true,
            rightAccuFlow: true,
            time: true,
        }).get({
            success: function(devRes) {
                // console.log('开采井数据',devRes)
                if (devRes.errMsg == "collection.get:ok" &&
                    devRes.data.length) {
                    var devData = devRes.data[0];

                    app.db.collection('nowData').where({
                        wellName: '刘庄回灌井',

                    }).orderBy('ts', 'desc').limit(1).field({
                        _id: false,
                        nowFlow: true,
                        rightAccuFlow: true,
                        time: true,
                    }).get({
                        success: function(bakRes) {
                            // console.log('开采井数据',devRes)
                            if (bakRes.errMsg == "collection.get:ok" &&
                                bakRes.data.length) {
                                var bakData = bakRes.data[0];


                                that.setData({
                                    nowDataTime: bakData.time,
                                    bakFlow: bakData.nowFlow,
                                    bakAccuFlow: bakData.rightAccuFlow,

                                    devFlow: devData.nowFlow,
                                    devAccuFlow: devData.rightAccuFlow,
                                    nowRate: Math.floor(bakData.nowFlow * 1000 / devData.nowFlow) / 10,
                                })

                            }
                        },
                        fail: console.error
                    })
                }
            },
            fail: console.error
        })
    },

    getHourData: function(e) {
        console.log('开始下载历史数据', e);
        var that = this;

        app.db.collection('hour').where({
            devWellName: '刘庄开采井',
            bakWellName: '刘庄回灌井',
        }).orderBy('startTs', 'desc').field({
            _id: false,
            endTime: true,

            devCount: true,
            devWellName: true,

            bakCount: true,
            bakWellName: true,
            bakRate: true,

            bakRate: true,
        }).get({
            success: function(hourRes) {
                console.log('历史数据长度:', hourRes.data.length)
                if (hourRes.errMsg == "collection.get:ok" &&
                    hourRes.data.length) {
                    var reversData = [];
                    for (var i = 0; i < hourRes.data.length; i++) {
                        reversData.push(hourRes.data[hourRes.data.length - i - 1]);
                    }
                    that.showChart(reversData);
                } else {
                    wx.showToast({
                        title: '暂无历史数据',
                        icon: 'loading',
                        duration: 2000
                    })

                }
            },
            fail: console.error
        })
    },

    showChart: function(hourData) {
        // console.log('showChart参数', e);

        var chartData = {
            titleText: '开采回灌流量和比例曲线',

            xAxisName: '时间',
            xAxisData: [],

            leftYAxisName: '瞬时流量',

            leftYSeries: [], //左Y轴数据集合
            // leftYSeriesData: [],//左纵轴控制的数据

            rightYAxisName: '回灌比例',
            rightSeriesName: '回灌比例',
            rightSeriesData: [],
        };


        //设置多采多回模式,本次暂不引入参数,以1采1灌进行
        var testGroup = [{
            name: '刘庄开采井',
            wellType: '开采井',
        }, {
            name: '刘庄回灌井',
            wellType: '回灌井',
        }]

        for (var i = 0; i < testGroup.length; i++) {
            chartData.leftYSeries.push({
                name: testGroup[i].name, // '所有的开采和所有的回灌流量',
                type: 'line',
                yAxisIndex: 0,

                data: [], // ,
                wellType: testGroup[i].wellType,

                label: {
                    show: false,
                    backgroundColor: '#EEEEEE',
                    fontSize: 16,
                    padding: 3,
                    position: 'top'
                },
            })
        }

        for (var i = 0; i < hourData.length; i++) {

            chartData.xAxisData.push(hourData[i].endTime.slice(11, 13) + '时');
            chartData.leftYSeries[0].data.push(hourData[i].devCount);
            chartData.leftYSeries[1].data.push(hourData[i].bakCount);


            chartData.rightSeriesData.push(hourData[i].bakRate);
        }

        var that = this;
        var pageEcComponentVar = 'pageEcVar';

        this[pageEcComponentVar] = this.selectComponent('#' + this.data.ecCanvasId);


        this[pageEcComponentVar].init((init_canvas, width, height, devicePixelRatio) => {
            const tmpEcChart = echarts.init(init_canvas, null, {
                width,
                height,
                devicePixelRatio,
            });

            var theOption = that.gnrtLineOption(chartData);

            tmpEcChart.setOption(theOption);

            that[that.data.ecCanvasId] = tmpEcChart;

            return tmpEcChart;
        });
    },

    gnrtLineOption: function(e) {
        var param = {
            titleText: '',

            xAxisName: '',
            xAxisData: [],

            leftYAxisName: '',

            leftSeriesName: '',
            leftSeriesData: [],

            rightYAxisName: '',
            rightSeriesName: '',
            rightSeriesData: [],
        }


        var legendData = []; //开采流量+回灌流量,回灌比例

        //把左纵轴所有的图标加上
        for (var i = 0; i < e.leftYSeries.length; i++) {
            legendData.push({
                name: e.leftYSeries[i].name,
                icon: 'circle',
                textStyle: {
                    color: '#333333'
                }
            })
        }

        //把右纵轴图例加上
        legendData.push({
            name: e.rightSeriesName,
            icon: 'circle',
            // backgroundColor: '#303F9F',
            textStyle: {
                color: '#333333'
            }
        })

        return {
            title: {
                text: e.titleText,
                left: 'center'
            },
            // color: ["#303F9F"],
            legend: {
                data: legendData,
                top: 30,
                left: 'center',
                orient: 'vertical',
                backgroundColor: 'rgba(255, 193, 7, 0.5)',
                // backgroundColor: '#FFC107',
                z: 10
            },
            grid: {
                containLabel: true
            },

            xAxis: {
                type: 'category',
                name: e.xAxisName,
                // name: '分钟:秒',
                nameLocation: 'middle',
                nameGap: 30,

                boundaryGap: false,

                axisLine: {
                    lineStyle: {
                        color: "#303F9F",
                    }
                },

                data: e.xAxisData,
                // axisLabel: {
                //     interval: 3,
                //     formatter: function(value) {
                //         return value;
                //     }
                // },

                splitArea: {
                    show: true,
                    areaStyle: {
                        color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
                    }
                }
            },

            yAxis: [{
                id: 0, //第一条纵轴,即左纵轴
                x: 'center',
                type: 'value',
                name: e.leftYAxisName, // '瞬时流量\nm3/h',
                position: 'left',
                axisLine: {
                    lineStyle: {
                        color: "#303F9F",
                    }
                },
                max: function(value) {
                    return Math.ceil(value.max / 10) * 10 + 20;
                },
                min: function(value) {
                    return Math.floor(value.min / 10) * 10 - 20;
                },
                show: true,
                // interval: 6,
                showMaxLabel: true,
                showMinLabel: true,
                splitArea: {
                    show: true,
                    areaStyle: {
                        color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
                    }
                }
            }, {
                id: 1, //第二条纵轴,即本右纵轴
                x: 'center',
                type: 'value',
                name: e.rightYAxisName, // '回灌比例',
                position: 'right',
                axisLine: {
                    lineStyle: {
                        color: "#303F9F",
                    }
                },
                max: function(value) {
                    return Math.ceil(value.max / 10) * 10 + 5;
                },
                min: function(value) {
                    return Math.floor(value.min / 10) * 10 - 5;
                },
                splitLine: {
                    show: false,
                }
                // interval: 100,
                // showMaxLabel: true,
                // showMinLabel: true,
            }],
            series: e.leftYSeries.concat({
                name: e.rightSeriesName, // '回灌比例',
                type: 'line',
                lineStyle: {
                    // color: '#303F9F',
                },
                yAxisIndex: 1,
                data: e.rightSeriesData, // totalFlow,
                label: {
                    show: false,
                    backgroundColor: '#EEEEEE',
                    fontSize: 16,
                    padding: 3,
                    position: 'top'
                },
            }),

            tooltip: {
                trigger: 'axis',
            },
        }
    },

    onHide: function() {
        clearTimeout(timerNum);
    },

    onUnload: function() {
        clearTimeout(timerNum);
    },

    onPullDownRefresh: function() {

    },

    onReachBottom: function() {

    },

    onShareAppMessage: function() {

    }
})